<?php
/**
 * Created by PhpStorm.
 * User: Qch
 * Date: 2017/3/25
 * Time: 15:56
 */

namespace J\Storage;


use J\IQueryablePersister;
use J\Util\Database;

/**
 *
 */
class ORM implements IQueryablePersister
{

    /**
     * @var Database
     */
    protected $eloquent;

    protected $table;

    /**
     * ORM constructor.
     * @param string $table 表名
     */
    public function __construct($table)
    {
        $this->table = $table;
        $this->eloquent = app()->Database();
    }

    /**
     * 获取
     * @param mixed $key
     * @param null $column
     * @return bool|array
     * @throws \Exception
     */
    public function get($key, $column = null)
    {
        $r = $this->getMulti($key,$column);

        if($r) return $r[(int)$key];

        return false;
    }

    /**
     * 批量获取
     * @param int[]|string[] $keys
     * @param null $column
     * @return array|false
     * @throws \Exception
     */
    public function getMulti($keys, $column = null)
    {
        return $this->eloquent->selectById($this->table,$column,$keys);
    }

    /**
     * 修改
     * @param mixed $pairs
     * @param null $keys
     * @return false|int
     * @throws \Exception
     */
    public function set($pairs, $keys = null)
    {
        return $this->eloquent->modify($this->table, $pairs, $keys);
    }

    /**
     * @param mixed $keys
     * @return int|false
     * @throws \Exception
     */
    public function delete($keys)
    {
        return $this->eloquent->delete($this->table,$keys);
    }

    /**
     * @param mixed $value
     * @return false|int
     * @throws \Exception
     */
    public function add($value)
    {
        return $this->eloquent->add($this->table, $value);
    }

    /**
     * 条件
     * @param $where
     * @param array $options
     * @return array|false
     * @throws \Exception
     */
    public function getKeys($where, $options = [])
    {
        $ids = $this->eloquent->getIds($this->table,$where, $options);
        return $ids;
    }

    public function getExpire($key)
    {
        return null;
    }

    /**
     * 查询
     * @param array|string $columns
     * @param array $conditions
     * @param array $option
     * @param  $fetch_model
     * @return array|false
     * @throws \Exception
     */
    public function query($columns, $conditions, $option = [], $fetch_model = null)
    {
        return $this->eloquent->query($this->table, $columns, $conditions, $option, $fetch_model);
    }
}